package com.geostar.constructionland.analyse.controller;

import com.geostar.constructionland.analyse.entity.geohandler.ErasureLandModel;
import com.geostar.constructionland.analyse.service.geohandler.GeoHandlerService;
import com.geostar.constructionland.common.entity.aly.AlyCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import sun.misc.BASE64Decoder;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Map;

/**
 * 空间坐标文件导出、空间坐标剔除功能
 *
 * @Author makoto_zhu
 * @Date 2020-11-23 02:40:07
 * @Description
 **/
@Controller
@Api("空间处理")
@RequestMapping("/geoHandler")
@Validated
public class GeoHandlerController {

    @Resource
    private GeoHandlerService geoHandlerService;

    @ApiOperation("导出合规红线")
    @RequestMapping(path = "/erasure")
    public void erasureLand(@Valid @RequestBody ErasureLandModel erasureLandModel, HttpServletResponse response) throws IOException {
        Map<String, Object> resultMap = null;
        try {
            resultMap = geoHandlerService.erasureLand(erasureLandModel);

            flushFile(erasureLandModel.getFxlx(), resultMap, response);
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(AlyCode.ERROR.getCode(), e.getMessage());
        }
    }

    /**
     * 导出mdb文件
     *
     * @param ywid
     * @param fxlx
     * @param response
     */
    @ApiOperation("导出mdb文件")
    @RequestMapping(path = "/exportMdb")
    public void exportMdb(@NotEmpty(message = "业务id不能为空") String ywid,
                          @NotEmpty(message = "分析类型不能为空") String fxlx,
                          HttpServletResponse response) throws IOException {
        Map<String, Object> resultMap = null;
        try {
            // 请求落图分析接口，将结果生成文件
            resultMap = geoHandlerService.exportMdb(ywid, fxlx);

            flushFile(fxlx, resultMap, response);
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(AlyCode.ERROR.getCode(), e.getMessage());
        }
    }


    private void flushFile(String fxlx, Map<String, Object> resultMap, HttpServletResponse response) throws IOException {
        if (resultMap.get("StatusCode") != null && "200".equals(resultMap.get("StatusCode").toString())) {
            String resultBytes = resultMap.get("ResultBytes").toString();

            String uniquetaskid = resultMap.get("UniqueTaskID").toString();
            String fileName = fxlx + "_" + uniquetaskid + ".mdb";

            BASE64Decoder decoder = new BASE64Decoder();
            byte[] bytes = decoder.decodeBuffer(resultBytes);

            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            response.setHeader("Access-Control-Expose-Headers", "filename");
            response.setHeader("filename", fileName);

            try (BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(bytes)); ServletOutputStream sos = response.getOutputStream()) {
                int len = 0;
                byte[] buffer = new byte[1 << 10];
                while ((len = bis.read(buffer)) != -1) {
                    sos.write(buffer, 0, len);
                }
                sos.flush();
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e.getMessage());
            }
        }
    }
}
